<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 17.12.2014
 * Time: 14:02
 */

namespace FlashMessages;



class DeleteListAction extends \Action {
	protected static $isPublic = true;
	
	public static function pullParams()
	{
		return ['identity'];
	}

	public function privileges(){
		return ['#authorized'];
	}

	/**
	 * http://pinenut.loc/flashMessages/deleteList?list=id1,id2,id3
	 */
	protected function run()
	{
		$this->response->noRender(true);
		$this->response->noCache(true);

		$myProfileId = $this->request->_identity;

		$deletedHashes = [];
		$list = $this->request->list;
		$hashList = explode(',', urldecode($list));
		$hashList = array_map(
			function($value){
				return trim($value);
			},
			$hashList
		);

		$messages = FlashMessage::getProfilesMessagesByHashList($myProfileId, $hashList);

		foreach ($messages as $message) {
			$message->isProcessed = true;
			$message->save();

			Queue::enqueue(
				[
					'type' => \FlashMessagesNotificationDeliveryConfig::FLASH_MESSAGE_REMOVED,
					'data' => [
						'flashMessageHash' => $message->hash,
						'targetProfileId' => (string)$message->profile,
					],
				]
			);

			$deletedHashes[] = $message->hash;
		}

		foreach ($hashList as $hash) {
			if (!in_array($hash, $deletedHashes)) {
				$deletedHashes[] = $hash;
			}
		}

		$this->response->content = json_encode($deletedHashes);
	}
}